<template>
  <el-dialog
    :title="dialogTitle"
    :visible.sync="dialogVisible"
    width="800px"
    append-to-body
    @close="handleClose"
  >
    <el-form ref="form" :model="formData" :rules="rules" label-width="80px">
      <!-- 名称 -->
      <el-form-item label="名称" prop="name">
        <el-input v-model="formData.name" />
      </el-form-item>

      <!-- 上传样本 -->
      <el-form-item label="上传样本" prop="storagePath">
        <el-button type="primary" @click="uploadFile">上传</el-button>
        <div v-if="formData.storagePath" class="mt-10">
          已上传文件路径:
          <span style="color: #1890ff">{{ formData.storagePath }}</span>
        </div>
        <div v-else class="mt-10" style="color: #999">尚未上传文件</div>
      </el-form-item>

      <!-- 挂卷地址 -->
      <el-form-item label="挂卷地址" prop="volumeAddress">
        <el-input
          v-model="formData.volumeAddress"
          placeholder="请输入挂卷地址，如：/mnt/data/volume1"
        />
      </el-form-item>

      <!-- 描述 -->
      <el-form-item label="描述">
        <el-input v-model="formData.description" type="textarea" :rows="3" />
      </el-form-item>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取 消</el-button>
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getToken } from "@/utils/auth";
import { mapState } from "vuex";

export default {
  name: "PerceptionSampleDialog",
  props: {
    visible: Boolean,
    data: Object, // 编辑时传入的数据，新增时为空
    sampleSetId: [String, Number], // 当前所属样本集 ID
  },
  data() {
    return {
      formData: {
        imageId: undefined,
        name: "",
        storagePath: "", // 文件存储路径（上传后回填）
        volumeAddress: "", // 挂卷地址
        fileSize: "", // 文件大小
        description: "",
        qualityAssessment: "", // 质量评估结果
        userId: null,
        sampleSetId: null,
      },
      rules: {
        name: [{ required: true, message: "名称不可为空", trigger: "blur" }],
        volumeAddress: [
          { required: true, message: "挂卷地址不能为空", trigger: "blur" },
          {
            pattern: /^\/.*$/,
            message: "挂卷地址必须是以 '/' 开头的合法路径",
            trigger: "blur",
          },
        ],
        storagePath: [
          { required: true, message: "请先上传样本文件", trigger: "change" },
        ],
      },
    };
  },
  computed: {
    ...mapState({
      userId: (state) => state.user.id,
    }),
    dialogTitle() {
      return this.formData.imageId ? "编辑" : "新增";
    },
    dialogVisible: {
      get() {
        return this.visible;
      },
      set(val) {
        this.$emit("update:visible", val);
      },
    },
  },
  watch: {
    visible: {
      immediate: true,
      handler(val) {
        if (val) {
          this.resetForm();
          if (this.data) {
            // 编辑模式：回填数据
            this.formData = { ...this.data };
          } else {
            // 新增模式：初始化
            this.formData.sampleSetId = this.sampleSetId;
            this.formData.userId = this.userId;
          }
        }
      },
    },
  },
  methods: {
    uploadFile() {
      this.$EventBus.$emit("openUploader", {
        token: getToken(),
        prefixFlag: 1,
        userId: this.$store.state.user.id,
      });
    },

    handleSubmit() {
      this.$refs.form.validate((valid) => {
        if (!valid) {
          this.$message.error("请完善表单信息，所有标红字段为必填项！");
          return;
        }

        // 提交数据（包含 userId）
        this.$emit("submit", { ...this.formData });
        this.handleClose();
      });
    },

    handleClose() {
      this.$emit("update:visible", false);
      this.$nextTick(() => {
        this.$refs.form?.resetFields(); // 重置校验状态
      });
    },

    resetForm() {
      this.formData = {
        imageId: undefined,
        name: "",
        storagePath: "",
        fileSize: "",
        volumeAddress: "",
        description: "",
        qualityAssessment: "",
        userId: this.userId,
        sampleSetId: this.sampleSetId,
      };
    },
  },
  mounted() {
    this.$EventBus.$on("fileSuccess", (response) => {
      if (response.code !== 200) {
        this.$message.error(response.msg);
        return;
      }
      this.$message.success("上传成功");
      // 填充文件路径和大小
      this.formData.storagePath = response.data.filePath;
      this.formData.fileSize = response.data.fileSize;

      // 手动触发表单校验（storagePath 是必填项）
      this.$refs.form?.validateField("storagePath");
    });
  },
  beforeDestroy() {
    this.$EventBus.$off("fileSuccess");
  },
};
</script>

<style scoped>
.mt-10 {
  margin-top: 10px;
  font-size: 13px;
}
.dialog-footer {
  text-align: right;
}
</style>
